var fs = require('fs');
 
function vcfToCsv(vcfStr) {
  // Split
  var lines = vcfStr.split('\r\n');
  var csvStr = '';
  var name = ''
  var numbers = [];
  var email = [];
  for(var l in lines) {
    line = lines[l];
    if (line[0] == 'N') {
      var parts = line.split(':');
      name = parts[parts.length - 1];
    }
 
    if (line.indexOf('TEL') == 0) {
      var parts = line.split(':');
      var num = parts[parts.length - 1];
      numbers.push(num);
    }
	if (line[3] == 'EMAIL') {
      var parts = line.split(':');
      var mail = parts[parts.length - 1];
    }
  }
 
  csvStr += name;
  for (var n in numbers) {
    csvStr += ',' + numbers[n];
  }
  csvStr += email;
  csvStr += '\n';
  return csvStr;
  
}
 
vcfList = [];
csvList = '';
args = process.argv;
synError = false;
vcfStartIndex = 2;
filesDone = 0;
 
if (args.length < 3)
{
  if (args.length == 2 && args[0] == "node")
    synError = true;
  else
    vcfStartIndex = 1;
}
 
if (synError) {
  console.log("Usage : \nnode <path-to-this-script> <path-to-vcf-file(s)>\nor\n<path-to-this-script> <path-to-vcf-file(s)");
  return;
}
 
vcfList = args.slice(vcfStartIndex);
 
vcfList.forEach(function(vcfFileName) {
                  fs.readFile(vcfFileName, 
                    function(err, data) {
                      if (err)
                        console.log(err.message);
 
                      csvStr = vcfToCsv(data.toString());
                      csvList += csvStr;
                      filesDone++;
                    });
                });
 
console.log("Processing : ");
 
function sleep() {
  setTimeout(writeCsv, 2000);
}
 
function writeCsv() {
  if (filesDone < vcfList.length) {
    console.log(".");
    sleep();
  }
  else {
    fs.writeFile('/path/to/output.csv', csvList.toString(),
                  function(err) {
                    if (err)
                      console.log(err.message);
                    else
                      console.log("CSV Saved\n");
                  });
  }
}
 
sleep();